import Koa from 'koa'
import cors from '@koa/cors'
import logger from 'koa-logger'
import bodyParser from 'koa-bodyparser'
import authRoutes from './routes/auth'
import jwt from 'koa-jwt'
import { jwtSecret } from './config/auth'

const app = new Koa()

/* 解决跨域 */
app.use(cors())
/* 解析请求体 */
app.use(bodyParser({
  enableTypes: [ 'json', 'form', 'text' ]
}))
/* 表示中间件日志 */
app.use(logger())

/* 解析路由 */
app.use(authRoutes.routes()).use(authRoutes.allowedMethods())

/* 自定义404错误 */
app.use((ctx, next) => {
  return next().catch(err => {
    if ( err.status === 401 ) {
      ctx.status = 401
      ctx.body = {
        code: 401,
        error: "未登录 token失效"
      }
    } else {
      ctx.throw(err)
    }
  })
})

/* 白名单配置 */
app.use(jwt(({ secret: jwtSecret})).unless({
  path: ['/api/auth/login', '/api/auth/register']
}))

const port = process.env.PORT || '3003'
app.listen(port, () => {
  console.log(`server listening on ${ port }`)
})
app.on('error', err => {
  console.error(`server err`, err)
})
